package com.pe.pgn.clubpgn.webapp.controller.bonomanual;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import com.pe.pgn.clubpgn.common.CLPConstantes;
import com.pe.pgn.clubpgn.domain.ClpbEstacion;
import com.pe.pgn.clubpgn.domain.ClpbEstadoCivil;
import com.pe.pgn.clubpgn.domain.ClpbPromocionBono;
import com.pe.pgn.clubpgn.domain.ClpdTipoBono;
import com.pe.pgn.clubpgn.domain.ClpmBonoClientePersona;
import com.pe.pgn.clubpgn.service.AfiliacionService;
import com.pe.pgn.clubpgn.service.ClientePersonaService;
import com.pe.pgn.clubpgn.service.PromocionBonoService;
import com.pe.pgn.clubpgn.service.BonoManualService;
import com.pe.pgn.clubpgn.service.TipoBonoService;
import com.pe.pgn.clubpgn.service.VentaService;
import com.pe.pgn.clubpgn.webapp.controller.BaseFormController;
import com.pe.pgn.clubpgn.webapp.util.CalendarUtil;

@Controller
@RequestMapping("/bonomanual/**")
public class BonoManualController extends BaseFormController{

	@Autowired 
	private BonoManualService bonoManualService;
	
	@Autowired 
	private TipoBonoService tipoBonoService;
	
	@Autowired 
	private PromocionBonoService promocionBonoService;
	
	@Autowired
	private AfiliacionService afiliacionService;
	
	@Autowired
	private VentaService ventaService; 
	
	@Autowired
	private ClientePersonaService clientePersonaService;
	
	@RequestMapping(value = "/bonosmanualeslist.html")
    public @ModelAttribute("bonosmanualesform") ClpmBonoClientePersona listarBonosManuales(
        	@ModelAttribute("bonosmanualesform") ClpmBonoClientePersona bonomanual, 
        	@RequestParam(value = "search", required = false) String search, Model model) {

		List<ClpdTipoBono> listTipoBono = tipoBonoService.listarTiposBono(true);
		
        if(StringUtils.isBlank(search)){
        	List<ClpmBonoClientePersona> listBonoManual = bonoManualService.listarBonosManuales();
        	model.addAttribute("listBonoManual", listBonoManual);
		}else{
			List<ClpmBonoClientePersona> listBonoManual = bonoManualService.buscarBonosManuales(bonomanual);
        	model.addAttribute("listBonoManual", listBonoManual);
		}
		
        model.addAttribute("listTipoBono", listTipoBono);
		return bonomanual;
    }
	
	@RequestMapping(value = "/bonosmanualesform.html", method = RequestMethod.POST)
	public String guardarBonoManual(@ModelAttribute("bonosmanualesform") ClpmBonoClientePersona bonomanual,
			BindingResult result, SessionStatus status, HttpServletRequest request, Model model) {

		try {
			
			bonomanual.setStPromocionActiva(true);
			List<ClpbPromocionBono> list = promocionBonoService.listarPromocionesBonoVigentes(true);
			model.addAttribute("listPromocionBono", list);
			
			if (result.hasErrors()) {
				model.addAttribute("bonosmanualesform", bonomanual);
				return "/bonomanual/bonosmanualesform";
			}
			
			Map<String, Object> mapMsg = bonoManualService.guardarBonoManual(bonomanual);
			if(mapMsg.get(CLPConstantes.MSG).equals(CLPConstantes.SUCCESS)){
				saveMessage(request, getText("common.added", request.getLocale()));
				return "redirect:bonosmanualeslist.html";
			}else{
				
				String detalle = String.valueOf(mapMsg.get("detalle"));
				if(detalle.equals("no_dentro_fechas_vigencia_promocion")){
				
					saveError(request, getText("bonosmanualesform.no.dentro.fechas.vigencia.promocion", request.getLocale()));
					return "/bonomanual/bonosmanualesform";
					
				}else if(detalle.equals("no_aplica_montomin")){
					
					saveError(request, getText("bonosmanualesform.no.aplica.montomin", request.getLocale()));
					return "/bonomanual/bonosmanualesform";
					
				}else if(detalle.equals("fecha_venta_no_menorigual_que_fecha_vigencia_prom")){
					
					saveError(request, getText("bonosmanualesform.fecha.venta.no.menorigual.que.fecha.vigencia.prom", request.getLocale()));
					return "/bonomanual/bonosmanualesform";
					
				}else if(detalle.equals("fecha_venta_no_menorigual_que_fecha_vencimiento")){
					
					saveError(request, getText("bonosmanualesform.fecha.venta.no.menorigual.que.fecha.vencimiento", request.getLocale()));
					return "/bonomanual/bonosmanualesform";
					
				}else if(detalle.equals("promocion_bono_bloqueada")){
					
					saveError(request, getText("bonosmanualesform.promocionbono.bloqueada", request.getLocale()));
					return "/bonomanual/bonosmanualesform";
					
				}else{
					
					saveError(request, getText("errors.general", request.getLocale()));
					return "/bonomanual/bonosmanualesform";
				}			
			}
			
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			return "/bonomanual/bonosmanualesform";
		}
	}
	
	@RequestMapping(value = "/eliminarbono.html")
	public String eliminarbono(@RequestParam(value = "id", required = false) Long id, 
			HttpServletRequest request, Model model) {

		try {

			int rowsDeleted = bonoManualService.eliminarBonoManual(id);
			if(rowsDeleted > 0){
				saveMessage(request, getText("common.deleted", request.getLocale()));
				return "redirect:bonosmanualeslist.html";
			}else{
				saveError(request, getText("errors.general", request.getLocale()));
				return "redirect:bonosmanualesform.html?id="+id;	
			}		
			
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			return "redirect:bonosmanualesform.html?id="+id;
		}
	}
	
	@RequestMapping(value = "/bonosmanualesform.html", method = RequestMethod.GET)
	public @ModelAttribute("bonosmanualesform") ClpmBonoClientePersona verBonoManual(
		   @RequestParam(value = "id", required = false) Long id, HttpServletRequest request, Model model) {
		
		ClpmBonoClientePersona bean  = new ClpmBonoClientePersona();
		List<ClpbPromocionBono> list = new ArrayList<ClpbPromocionBono>();
		
		try{
		
			list = promocionBonoService.listarPromocionesBonoVigentes(true);
			
			if (id != null) {
				bean = bonoManualService.obtenerBonoManual(id);
				
				if(bean.getDeVentaGeneracion() == null || "".equals(bean.getDeVentaGeneracion())){
					bean.setDeVentaGeneracion("----");
				}
				
				if((bean.getDeVentaConsumo() == null || "".equals(bean.getDeVentaConsumo())) &&
				   (bean.isStUsado() || !bean.isStBonoClientePersona() || CLPConstantes.WEBSERVICE.equals(bean.getStTipoGeneracion()))){
					bean.setDeVentaConsumo("----");
				}
				
				for (ClpbPromocionBono clpbPromocionBono : list) {
					String idPromocionBono = clpbPromocionBono.getId().toString();
					
					if(bean.getCoPromocionBono().equals(idPromocionBono)){
						bean.setStPromocionActiva(true);
						break;
					}
				}
				
			}else{
				
				String fechaGeneracion = CalendarUtil.getDate(CLPConstantes.DATE_PATTERN);
				bean.setStBonoClientePersona(true);
				
				bean.setDeTipoBono("----");
				bean.setCoTipoBono("-1");
				bean.setFechaVencimiento("----");
				bean.setDeTipoGeneracion(CLPConstantes.DE_MANUAL);
				bean.setStTipoGeneracion(CLPConstantes.MANUAL);
				bean.setFechaGeneracion(fechaGeneracion);
			}		
		
		}catch(Exception e){
			saveError(request, getText("errors.general", request.getLocale()));
		}
		
		model.addAttribute("listPromocionBono", list);
		model.addAttribute("bonosmanualesform", bean);
		return bean;
	}
	
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/buscarclientespersona.html", method = RequestMethod.GET)
	public String buscarClientesPersona(HttpServletRequest request, Model model) {
		
		List listDep  = null;
		List listProv = null;
		List listDist = null;
		List<ClpbEstadoCivil> estadoCivil = null;
		
		try {
		
		estadoCivil = clientePersonaService.listarEstadosCiviles(true);
		listDep = afiliacionService.findDepartamentosUbigeo(true);		
		listProv = afiliacionService.findPronvinciaUbigeo(null, true);
		listDist = afiliacionService.findDistritoUbigeo(null, null, true);
	
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
		}
		
		model.addAttribute("listadepartamento"  , listDep);
		model.addAttribute("listaprovincia"	    , listProv);
		model.addAttribute("listadistrito"	    , listDist);
		model.addAttribute("listestadocivil"	, estadoCivil);
		return "/wizard/clientepersonawizardform";
	}
	
	@RequestMapping(value = "/buscarventasgeneracion.html", method = RequestMethod.GET)
	public String  buscarVentasGeneracion(
		@RequestParam(value = "coClientePersona", required = true) String coClientePersona,
		@RequestParam(value = "deClientePersona", required = false) String deClientePersona,
		HttpServletRequest request, Model model) {
		
		List<ClpbEstacion> estaciones = null;
		
		try {
		
			estaciones = ventaService.listarEstaciones(true);
	
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
		}
		
		model.addAttribute("listEstaciones", estaciones);
		model.addAttribute("coClientePersona", coClientePersona);
		model.addAttribute("deClientePersona", deClientePersona);
		return "/wizard/ventasgeneracionwizardform";
	}
	
	@RequestMapping(value = "/buscarventasconsumo.html", method = RequestMethod.GET)
	public String  buscarVentasConsumo(
		@RequestParam(value = "coClientePersona", required = true) String coClientePersona,
		@RequestParam(value = "deClientePersona", required = false) String deClientePersona,
		HttpServletRequest request, Model model) {
		
		List<ClpbEstacion> estaciones = null;
		
		try {
		
			estaciones = ventaService.listarEstaciones(true);
	
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
		}
		
		model.addAttribute("listEstaciones", estaciones);
		model.addAttribute("coClientePersona", coClientePersona);
		model.addAttribute("deClientePersona", deClientePersona);
		return "/wizard/ventasconsumowizardform";
	}
}
